package com.hw.hcit.feature;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.hw.hcit.R;
import com.hw.hcit.conf.Config;
import com.hw.hcit.conf.JCtrlCallback;
import com.hw.hcit.conf.JTestItem;

public class BluetoothTest extends JTestItem implements OnClickListener {
	private static final String TAG = "BluetoothTest ";
	private static final String NAME = "name";
	private static final String ADDRESS = "address";
	private Context mContext;
	private ListView mListView;
	private SimpleAdapter mSimpleAdapter;
	Set<BluetoothDevice> bondedDevices;
	BluetoothAdapter mBluetoothAdapter = null;
	private boolean bReScanned = false;
	private boolean mPowerClicked;
	private boolean mTested;
	private Button mButton1,mButton2;
	private TextView textView;
	 /*gaoshenpan 15-08-24 fix no bluetooth scan 2times to find bluetooth begin*/
	private static int testCount = 0;
	 /*gaoshenpan 15-08-24 fix no bluetooth scan 2times to find bluetooth end*/
	

	ArrayList<HashMap<String, String>> mBluetoothInfoList = new ArrayList<HashMap<String, String>>();

	public BluetoothTest(JCtrlCallback cb) {
		super(cb);
	}

	public BluetoothTest() {
		super();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.bluetooth_test, container,
				false);
		mListView = (ListView) rootView.findViewById(R.id.bluetooth_list);
		mSimpleAdapter = new SimpleAdapter(mContext, mBluetoothInfoList,
				R.layout.bluetooth_list_item, new String[] { NAME, ADDRESS },
				new int[] { R.id.device_name, R.id.device_address });
		mListView.setAdapter(mSimpleAdapter);
		textView = (TextView) rootView.findViewById(R.id.textView1);
		mButton1 = (Button) rootView.findViewById(R.id.button1);
		mButton2 = (Button) rootView.findViewById(R.id.button2);
		mButton1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if(Config.CURR_PROJECT.isAuto()){
					if (!Config.ageingTested) {
						rewriteOneByteOfNv2499(22, 'P');
					} else {
						rewriteOneByteOfNv2499(53, 'P');
					}
				}
				 testFinish(true, 1, true);
				
			}
		});
		mButton2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if(Config.CURR_PROJECT.isAuto()){
					if (!Config.ageingTested) {
						rewriteOneByteOfNv2499(22, 'F');
					} else {
						rewriteOneByteOfNv2499(53, 'F');
					}
				}
				testFinish(false, 1, false);
				
			}
		});
		return rootView;
	}

	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		mContext = activity;
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		mButton1.setEnabled(false);
		mButton2.setEnabled(false);
		 /*gaoshenpan 15-08-24 fix no bluetooth scan 2times to find bluetooth begin*/
		testCount = 0;
		startScanAdapterUpdate();
		IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
		filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
		filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
		mContext.registerReceiver(mReceiver, filter);	
		 /*gaoshenpan 15-08-24 fix no bluetooth scan 2times to find bluetooth end*/
		bReScanned = false;
		mPowerClicked = false;
		mTested = false;
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		mContext.unregisterReceiver(mReceiver);
	}

	@Override
	public boolean getResult() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public String getResultInfo() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void startTest() {
		// TODO Auto-generated method stub

	}

	@Override
	public void stopTest() {
		// TODO Auto-generated method stub

	}

	public void refresh() {

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
	}

	private void scanDevice() {
		// setProgressBarIndeterminateVisibility(true);
		if (mBluetoothAdapter.isDiscovering()) {
			mBluetoothAdapter.cancelDiscovery();
		}
		mBluetoothAdapter.startDiscovery();
	}

	private void cancelScan() {
		// setProgressBarIndeterminateVisibility(false);
		if (mBluetoothAdapter.isDiscovering()) {
			mBluetoothAdapter.cancelDiscovery();
		}
	}

	public void updateAdapter() {
		mSimpleAdapter.notifyDataSetChanged();
	}

	private void startScanAdapterUpdate() {
		mBluetoothInfoList.clear();
		bondedDevices = mBluetoothAdapter.getBondedDevices();
		HashMap<String, String> bluetoothInfo = new HashMap<String, String>();
		for (BluetoothDevice device : bondedDevices) {
			Log.d(TAG, TAG + "device.name = " + device.getName()
					+ " device.address" + device.getAddress());
			if(device.getName()!=null && "hybluetooth".equals(device.getName())){
				bluetoothInfo.put(NAME, device.getName());
				bluetoothInfo.put(ADDRESS, device.getAddress());
				if(!mBluetoothInfoList.contains(bluetoothInfo)){
					mBluetoothInfoList.add(bluetoothInfo);
				}
				
				mButton1.setEnabled(true);
				mButton2.setEnabled(false);
				textView.setText(getString(R.string.bluetooth_scan_success));
				
			}
		}
		updateAdapter();
		if (mBluetoothAdapter.getState() == BluetoothAdapter.STATE_ON) {
			scanDevice();
		}
	}

	BroadcastReceiver mReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {

			String action = intent.getAction();
			BluetoothDevice device = intent
					.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
			Log.d(TAG, TAG + "intent.actoin = " + action + " device = "
					+ device);
			HashMap<String, String> bluetoothInfo = new HashMap<String, String>();
			if (BluetoothDevice.ACTION_FOUND.equals(action)) {
				if(device.getName()!=null && "hybluetooth".equals(device.getName())){
				bluetoothInfo.put(NAME, device.getName());
				bluetoothInfo.put(ADDRESS, device.getAddress());
				if(!mBluetoothInfoList.contains(bluetoothInfo)){
					mBluetoothInfoList.add(bluetoothInfo);
				}
				
				mButton1.setEnabled(true);
				mButton2.setEnabled(false);
				textView.setText(getString(R.string.bluetooth_scan_success));
				}
				updateAdapter();
			} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
					.equals(action)) {
				 /*gaoshenpan 15-08-24 fix no bluetooth scan 2times to find bluetooth begin*/
				Log.d(TAG,  "testCount = " +"2");
				if(mBluetoothInfoList.size()==0){
					if(testCount == 0){
						Log.d(TAG,  "testCount = " +mBluetoothInfoList.size()+"----"+"0");
						testCount++;
						startScanAdapterUpdate();
					}else{
						Log.d(TAG,  "testCount = " +mBluetoothInfoList.size()+"----"+"1");
						Toast.makeText(mContext, "Scan finished...", Toast.LENGTH_SHORT)
						.show();
				       mButton1.setEnabled(false);
				       mButton2.setEnabled(true);
				       textView.setText(getString(R.string.bluetooth_scan_fail));
					}	
				}else{
					Toast.makeText(mContext, "Scan finished...", Toast.LENGTH_SHORT)
					.show();
				}
				/*gaoshenpan 15-08-24 fix no bluetooth scan 2times to find bluetooth end*/
				
			} else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
				Toast.makeText(mContext, "Start scan...", Toast.LENGTH_SHORT)
						.show();
			} else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
				if (BluetoothAdapter.STATE_ON == intent.getIntExtra(
						BluetoothAdapter.EXTRA_STATE, 0)) {
					startScanAdapterUpdate();
				} else if (BluetoothAdapter.STATE_OFF == intent.getIntExtra(
						BluetoothAdapter.EXTRA_STATE, 0)) {
					// mBluetoothAdapter.enable();
				} else if (BluetoothAdapter.STATE_TURNING_ON == intent
						.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0)) {
					Toast.makeText(mContext, "Enabling bluetooth...",
							Toast.LENGTH_SHORT).show();
				}
			}
		}// onReceive

	};

	 @Override
	    public boolean dispatchKeyEvent(KeyEvent event) {
	        // TODO Auto-generated method stub
	        return true;
	    }
	/*@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		// TODO Auto-generated method stub
		if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN) {
			if (mPowerClicked) {
				testFinish(false, 1, false);
				return true;
			}
			if (!mTested) {
				showTestUncomplete();
				return true;
			}
		} else if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
			mPowerClicked = true;
			showPowerClicked();
			return true;
		}
		return super.dispatchKeyEvent(event);
	}*/

}
